import ajax from "./ajax.js";
let obj = {
  url: "https://api.iynn.cn/mock?t=2",
};
let dataArr = [];

if (!localStorage.getItem("It")) {
  ajax(obj).then((res) => {
    console.log(res);
    dataArr = res.data;
    localStorage.setItem("It", JSON.stringify(dataArr));
    console.log("走ajax");
    render(dataArr);
  });
} else {
  dataArr = JSON.parse(localStorage.getItem("It"));
  console.log("走缓存");
  render(dataArr);
}
function render(arr) {
  let str = `<tr>
    <th>序号</th>
    <th>标题</th>
    <th>发布</th>
    <th>发布时间</th>
    <th>操作</th>
  </tr>`;
  arr.forEach((item) => {
    str += `
    <tr>
    <td>${item.id}</td>
    <td>${item.title}</td>
    <td>${item.user}</td>
    <td>${item.date}</td>
    <td><div class='del'>删除</div><div class='change'>编辑</div></td>
  </tr>
    `;
  });
  document.querySelector("table").innerHTML = str;
  change0();
  delete0();
}
let add = document.querySelector(".add");
let title = document.querySelector(".title");
let author = document.querySelector(".author");
let date = document.querySelector(".date");

add.addEventListener("click", () => {
  dataArr.push({
    id: dataArr[dataArr.length - 1].id * 1 + 1,
    title: title.value,
    user: author.value,
    date: date.value,
  });
  localStorage.setItem("It", JSON.stringify(dataArr));
  render(dataArr);
});
function delete0() {
  let del = document.querySelectorAll(".del");
  del.forEach((item, index) => {
    item.addEventListener("click", () => {
      dataArr.splice(index, 1);
      localStorage.setItem("It", JSON.stringify(dataArr));
      render(dataArr);
    });
  });
}

function change0() {
  let change = document.querySelectorAll(".change");
  let titleNew = document.querySelector(".titleNew");
  let authorNew = document.querySelector(".authorNew");
  let dateNew = document.querySelector(".dateNew");
  let addsure = document.querySelector(".addsure");

  change.forEach((item, index) => {
    console.log(item);
    item.addEventListener("click", () => {
      console.log(item);
      titleNew.value = dataArr[index].title;
      authorNew.value = dataArr[index].user;
      dateNew.value = dataArr[index].date;

      $("#myModal").modal("show");
      addsure.addEventListener("click", () => {
        console.log(item);
        dataArr[index].title = titleNew.value;
        dataArr[index].user = authorNew.value;
        dataArr[index].date = dateNew.value;
        localStorage.setItem("It", JSON.stringify(dataArr));
        render(dataArr);
      });
    });
  });
}
